package com.OneCommerceProject.controllers;

import com.OneCommerceProject.beans.CaracteristiqueFacade;
import com.OneCommerceProject.beans.FournisseurFacade;
import com.OneCommerceProject.beans.ItemFacade;
import com.OneCommerceProject.beans.ItemFourFacade;
import com.OneCommerceProject.beans.PhotosFacade;
import com.OneCommerceProject.beans.PrixFacade;
import com.OneCommerceProject.controllers.util.JsfUtil;
import com.OneCommerceProject.controllers.util.PaginationHelper;
import com.OneCommerceProject.entities.*;
import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.event.AbortProcessingException;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.event.FlowEvent;
import org.primefaces.event.TabChangeEvent;
import org.primefaces.model.UploadedFile;

@ManagedBean(name = "itemController")
@SessionScoped
public class ItemController implements Serializable {

    private Item current;
    private Photos photo;
    private Prix prix;
    private ItemFour itemFour;
    private Fournisseur fournisseur = new Fournisseur();
    private Caracteristique caracteristique = new Caracteristique();
    private List<Caracteristique> listCaracteristiques = new ArrayList<Caracteristique>();
    private UploadedFile file;
    private DataModel items = null;
    @EJB
    private com.OneCommerceProject.beans.ItemFacade ejbFacade;
    @EJB
    private PhotosFacade photoFacade;
    @EJB
    private PrixFacade prixFacade;
    @EJB
    private FournisseurFacade fournisseurFacade;
    @EJB
    private CaracteristiqueFacade caracteristiqueFacade;
    @EJB
    private ItemFourFacade itemFourFacade;
    private PaginationHelper pagination;
    private int selectedItemIndex;
    private BigDecimal somme;
    private boolean chooseFour = false;
    private List<Fournisseur> listFournisseur;
//    private boolean leader = true;
//    private String nomFour;
//
//    public String getNomFour() {
//        return nomFour;
//    }
//
//    public void setNomFour(String nomFour) {
//        this.nomFour = nomFour;
//    }
//

    public boolean isChooseFour() {
        return chooseFour;
    }
//
//    public boolean isLeader() {
//        return leader;
//    }
//
//    public void setLeader(boolean leader) {
//        this.leader = leader;
//    }

    public void onTabChange(TabChangeEvent event) {
        chooseFour = !chooseFour;
        System.out.println("chooseFour: " + chooseFour);
    }

    public List<Fournisseur> getListFournisseur() {
        listFournisseur = getFournisseurFacade().findAll();
        return listFournisseur;
    }

    public BigDecimal getSomme() {
        return somme;
    }

    public void setSomme(BigDecimal somme) {
        this.somme = somme;
    }

    public Fournisseur getFournisseur() {
        return fournisseur;
    }

    public void setFournisseur(Fournisseur fournisseur) {
        this.fournisseur = fournisseur;
    }

    public Caracteristique getCaracteristique() {
        return caracteristique;
    }

    public void setCaracteristique(Caracteristique caracteristique) {
        this.caracteristique = caracteristique;
    }

    public String onFlowProcess(FlowEvent event) {
        return event.getNewStep();
    }

    public void saveFileUpload() throws FileNotFoundException, IOException {
        photo = new Photos();
        String filename = file.getFileName();
        photo.setFilename(filename);
        String path = current.getNomitem();
        photo.setPhotopath(path + "\\" + filename);
        path = System.getenv("USERPROFILE") + "\\Documents\\OneCommerceImages\\"+current.getNomitem();
        new File(path).mkdir();
        FileOutputStream outputStream = new FileOutputStream(new File(path, filename));
        outputStream.write(file.getContents());
        outputStream.close();
        current.getPhotosCollection().add(photo);
        photo.setIditem(current);
        getPhotosFacade().create(photo);
        JsfUtil.addSuccessMessage(filename + " " + ResourceBundle.getBundle("/Bundle").getString("PhotosCreated"));
    }

    public void processFileUpload(FileUploadEvent e) throws AbortProcessingException, IOException {
        file = e.getFile();
    }

    private void intiatePrix() {
        prix = new Prix();
        prix.setSomme(somme);
        prix.setIditem(current);
        java.util.Date today = new java.util.Date();
        prix.setDateprix(new Date(today.getTime()));
        current.getPrixCollection().add(prix);
        getPrixFacade().create(prix);
    }

    public void addCaracteristic() {
        caracteristique.setIditem(current);
        listCaracteristiques.add(caracteristique);
        JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("CaracteristiqueCreated"));
        caracteristique = new Caracteristique();
    }

    public ItemController() {
    }

    public Item getSelected() {
        if (current == null) {
            current = new Item();
            selectedItemIndex = -1;
        }
        return current;
    }

    private ItemFacade getFacade() {
        return ejbFacade;
    }

    private PhotosFacade getPhotosFacade() {
        return photoFacade;
    }

    private PrixFacade getPrixFacade() {
        return prixFacade;
    }

    private FournisseurFacade getFournisseurFacade() {
        return fournisseurFacade;
    }

    private CaracteristiqueFacade getCaracteristiqueFacade() {
        return caracteristiqueFacade;
    }

    private ItemFourFacade getItemFourFacade() {
        return itemFourFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {

                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        recreateModel();
        return "List";
    }

    public String prepareView() {
        current = (Item) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }

    public String prepareCreate() {
        current = new Item();
        fournisseur = new Fournisseur();
        caracteristique = new Caracteristique();
        listCaracteristiques = new ArrayList<Caracteristique>();
        prix = new Prix();
        photo = new Photos();
        selectedItemIndex = -1;
        return "Create";
    }

    public void createItemFour() {
        itemFour = new ItemFour();
        itemFour.setFournisseur(fournisseur);
        itemFour.setItem(current);
        itemFour.setLeader(true);
        ItemFourPK itemFourPK = new ItemFourPK(current.getIditem(), fournisseur.getIdfour());
        itemFour.setItemFourPK(itemFourPK);
        System.out.println("itemFour: " + itemFour);
        getItemFourFacade().create(itemFour);
    }

    public String create() {
        try {
            current.setNbreVente(BigInteger.ZERO);
            if (chooseFour) {
                getFournisseurFacade().create(fournisseur);
//            } else {                                
//                if (leader) {
//                    ItemFour itemFourLeader = getItemFourFacade().findItemLeader(current.getIditem());
//                    itemFourLeader.setLeader(false);
//                    getItemFourFacade().edit(itemFourLeader);
//                }
            }
            getFacade().create(current);
            createItemFour();
            for (int i = 0; i < listCaracteristiques.size(); i++) {
                if (listCaracteristiques.get(i) != null) {
                    getCaracteristiqueFacade().create(listCaracteristiques.get(i));
                }
            }
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ItemCreated"));
            saveFileUpload();
            intiatePrix();
            chooseFour = false;
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit() {
        current = (Item) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "/pages/item/Edit";
    }

    public String prepareEdit2() {
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        String itemId = externalContext.getRequestParameterMap().get("item");
        current = getFacade().findByIdItem(new BigDecimal(itemId));
//        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "/pages/item/Edit.xhtml?faces-redirect=true";
    }

    public String update() {
        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ItemUpdated"));
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy() {
        current = (Item) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreatePagination();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("ItemDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    public BigInteger getQuantiteItemById(BigDecimal id) {
        return ejbFacade.find(id).getQuantiteitem();
    }

    private void recreateModel() {
        items = null;
    }

    private void recreatePagination() {
        pagination = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    @FacesConverter(forClass = Item.class)
    public static class ItemControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            ItemController controller = (ItemController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "itemController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.math.BigDecimal getKey(String value) {
            java.math.BigDecimal key;
            key = new java.math.BigDecimal(value);
            return key;
        }

        String getStringKey(java.math.BigDecimal value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Item) {
                Item o = (Item) object;
                return getStringKey(o.getIditem());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + ItemController.class.getName());
            }
        }
    }
}
